import otherHelpers from "./others";

const nativeWin = otherHelpers.globalWin;
const callbacks = [];

function beforeUnload() {
    nativeWin?.removeEventListener('beforeunload', beforeUnload);
    callbacks.forEach(cb => cb.action.call(cb.thisArg ?? null));
    callbacks.splice(0, callbacks.length);
}

let isRegistered = false;

export default function autoDisposeWhenUnload(dispose, thisArg) {
    let index = -1;

    if (!!nativeWin) {
        if (!isRegistered) {
            nativeWin?.addEventListener('beforeunload', beforeUnload);
            isRegistered = true;
        }

        index = callbacks.findIndex(cb => dispose === cb.action && thisArg === cb.thisArg);
        if (-1 === index) {
            callbacks.push({
                action: dispose,
                thisArg,
            });
            index = callbacks.length;
        }
    }

    return () => {
        dispose.call(thisArg ?? null);
        callbacks.splice(index, 1);
    };
}
